package cn.wolfcode.trip.admin.Controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地区资源控制器
 */
@Controller
@RequestMapping("/region")
public class RegionController {

    @Autowired
    private IRegionService regionService;


    /**
     * 仅用于页面跳转
     * @return
     */
    @RequestMapping("/list")
    public String list(){
        return "region/list";
    }

    /**
     * 获取所有地区
     * @return
     */
    //获取所有地区
    @ResponseBody
    @RequestMapping("listAll")
    public List<Region> getRegion (){
        return regionService.listAll();
    }

    /**
     * 通过父地区id查出该父地区的子地区
     * @param parentId
     * @param status
     * @return
     */
    @RequestMapping("/selectByParentId")
    @ResponseBody
    public Object selectByParentId(Long parentId,String status){
        List<Region> listRegion=regionService.selectForList(parentId);
        if ("tree".equals(status)) {
            List<Map<String,Object>> list =new ArrayList<>();
            for (Region r:listRegion) {
                Map nodes = r.toMap();
                list.add(nodes);
            }
            System.out.println(list);
            return list;
        }else{
            System.out.println(listRegion);
            return listRegion;
        }

    }

    /**
     * 修改或保存地区
     * @param region
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region){
        JSONResult jsonResult = new JSONResult();
        try {
            regionService.saveOrUpdate(region);
        } catch (Exception e) {
            jsonResult.mark("保存失败,请稍后再试");
            e.printStackTrace();
        }

        return  jsonResult;
    }

    /**
     * 修改地区的状态(推荐)
     * @param status
     * @param id
     * @return
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    public Object updateStatus(Integer status,Long id){

        JSONResult jsonResult = new JSONResult();
        try {
             regionService.updateStatus(status,id);
        } catch (Exception e) {
            jsonResult.mark("操作失败,请稍后再试");
            e.printStackTrace();
        }

        return  jsonResult;
    }
}
